package com.gupao;

import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyBlockedQueue {
    List<Object> list = new ArrayList<>();
    Object lock = new Object();
    int maxSize;

    public MyBlockedQueue(int maxSize) {
        this.maxSize = maxSize;
    }

    public void put(Object element) {
        synchronized (lock) {
            if (list.size() == maxSize) {
                System.out.println(Thread.currentThread().getName() + "-->" + "队列满了");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // put
            list.add(element);
            System.out.println(Thread.currentThread().getName() + "-->" + "添加了元素：" + element);
            lock.notifyAll();
        }
    }

    public Object get() {
        synchronized (lock) {
            if (list.isEmpty()) {
                System.out.println(Thread.currentThread().getName() + "-->" + "队列空了");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Object element = list.remove(0);
            System.out.println(Thread.currentThread().getName() + "-->" + "取走了元素：" + element);
            lock.notifyAll();
            return element;

        }
    }

    static ExecutorService pool = Executors.newCachedThreadPool();

    public static void main(String[] args) {
        MyBlockedQueue queue = new MyBlockedQueue(1);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        pool.submit(() -> {
            for (int i = 0; i < 10; i++) {
                queue.put(i);
            }
        });
        pool.submit(() -> {
            while (true)
                try {
                    reader.readLine();
                    queue.get();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        });
    }

}
